package com.maestro.sss;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class GameRandom extends Activity {
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.random);
        
        Button btnGet = (Button) findViewById(R.id.button1);
        btnGet.setOnClickListener( new View.OnClickListener() {
			public void onClick(View v) { onGetData(); }
		});
	}
	
	public void onGetData() {
		TextView tv = (TextView) findViewById(R.id.textView2);
		StringBuffer sbResult = new StringBuffer();
		
		try {
			URL url;
			URLConnection urlConn; 
			DataInputStream dis;
			
			url = new URL("http://loslch.cafe24.com/random/json.php");
			
			urlConn = url.openConnection();
			urlConn.setReadTimeout(3000);
			urlConn.setDoInput(true); 
			urlConn.setUseCaches(false);
			
			dis = new DataInputStream(urlConn.getInputStream());
			
			String szInputLine;
			while((szInputLine=dis.readLine()) != null) {
				sbResult.append(szInputLine);
			}
			dis.close();
			
		}	
		catch (MalformedURLException e) {Log.d("FOOD", e.toString());} 
		catch (IOException e) {Log.d("FOOD", e.toString());}
		
		JSONParser parser = new JSONParser();
		KeyFinder finder = new KeyFinder();
		finder.setMatchKey("name");
		try {
			parser.parse(sbResult.toString(), finder, true);
			if(finder.isFound()){
				finder.setFound(false);
				tv.setText(finder.getValue().toString());
			}else{
				tv.setText("Not founded.");
			}
		}
		catch (ParseException e) {Log.d("FOOD", e.toString());}
		
	}
}
